import sys, os
import socket
from Ui_sendemail import  *
from PyQt4 import QtCore, QtGui
from datetime import datetime

def createClient(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error as msg:
        print("socket creat error:", msg)
        sys.exit()
    try:
        ip = socket.gethostbyname(host)
        sock.connect((ip, port))
    except socket.error as msg:
        print("connect {0}:{1} error:{2}".format(host, port, msg))
        sock.close()
        sys.exit()
    print("client sock ok!")
    return sock
    
def buildInfo(to, path):
    size = os.path.getsize(path)
    data = "id:B99003001;"+"to:"+to+";"+"size:"+str(size)+";"+"path:"+path
    data += ";from:John;body:meeting!;head:alarm-"+datetime.now().isoformat(' ')
    return data
    
def sendEmailReq(tolist, path, host, port):
    info = buildInfo(tolist, path)
    sock = createClient(host, port)
    # in Python3x must explicit convert string to bytes
    sock.sendall(bytes(info, "utf-8"))
    # recv attach file name to send attach data
    fname = sock.recv(1024)
    with open(fname.decode('utf-8'), "rb") as f:
        sock.sendall(f.read())
    resp = sock.recv(1024)
    print("email send resp:", resp.decode('utf-8'))
    sock.close()
    
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

class Ui_Client(Ui_Dialog):
    def sendSlot(self):
        if self.tolistLedt.text()=='':
            QtGui.QMessageBox.warning(Dialog,_fromUtf8("错误信息"), _fromUtf8("收件人不能为空！"))
        elif self.attachLedt.text()=='' :
            QtGui.QMessageBox.warning(Dialog,_fromUtf8("错误信息"), _fromUtf8("附件不能为空！"))
        else:
            sendEmailReq(self.tolistLedt.text(), self.attachLedt.text(),'localhost', 7777 )
            
    def selectSlot(self):
        self.attach = QtGui.QFileDialog.getOpenFileName(Dialog, _fromUtf8("选择文件"))
        self.attachLedt.setText(self.attach)
        
    def initUi(self):
        QtCore.QObject.connect(self.selectBtn, QtCore.SIGNAL(_fromUtf8("clicked()")), self.selectSlot)
        QtCore.QObject.connect(self.sendBtn, QtCore.SIGNAL(_fromUtf8("clicked()")), self.sendSlot)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
        
if __name__ == "__main__":
#    sendEmailReq("George,bruce", "F:\\python\\IMGP1772.JPG",'localhost', 7777 )
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Client()
    ui.setupUi(Dialog)
    ui.initUi()
    Dialog.show()
    sys.exit(app.exec_())
